package com.spm.librarianmanagersystem.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


public class EmailUtil {

    public final static String MESSAGE_TYPE = "text/html;";
    public final static String CODING_TYPE = "charset=gb2312";

    /**
     * 发送短信工具类
     *
     * @param receiver 接受方
     * @param subject  主题
     * @param context  内容
     * @param type     1.html; 2.text
     */

    public static void sendEmail(String receiver, String subject, String context, String type) throws Exception {

        String from = "3043462045@qq.com";
        String host = "smtp.qq.com";

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");

        // 建立会话，使用密码验证机制
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                {
                    //发件人邮件用户名、授权码
                    return new PasswordAuthentication("3043462045@qq.com", "hegcgkuihhlfdgec");
                }
            }
        });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(receiver));
        message.setSubject(subject);

        if (type.equals("html")) {
            // 发送html类型邮件
            message.setContent(context, MESSAGE_TYPE + CODING_TYPE);
        } else if (type.equals("text")) {
            // 发送村纯文本邮件
            message.setText("This is actual message");
        } else {
            throw new RuntimeException("类型参数异常");
        }
        Transport.send(message);

        System.out.println("Sent message successfully");

    }
}
